#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author： 胡浩浩
# datetime： 2021/12/14 16:05 
# ide： PyCharm
from fastapi import FastAPI, Request, Response

from Tools.database import SessionLocal
from Views.apiView import api_view
from Views.assetView import asset_view
from Views.userView import user_view
from Views.environmentView import environment_view
from Views.caseView import case_view
import uvicorn

app = FastAPI(
    title="ApiAutoTestPlatform",
    description="ApiAutoTestPlatform API helps you do awesome stuff. 🚀",
    version="0.0.1"
)
app.include_router(api_view.router,
                   prefix="/apis",
                   tags=["ApiManage"],
                   responses={404: {"description": "Not found"}},
                   )
app.include_router(asset_view.router,
                   prefix="/assets",
                   tags=["AssetManage"],
                   responses={404: {"description": "Not found"}},
                   )
app.include_router(user_view.router,
                   prefix="/users",
                   tags=["UserManage"],
                   responses={404: {"description": "Not found"}},
                   )
app.include_router(environment_view.router,
                   prefix="/environments",
                   tags=["EnvironmentManage"],
                   responses={404: {"description": "Not found"}},
                   )
app.include_router(case_view.router,
                   prefix="/cases",
                   tags=["CaseManage"],
                   responses={404: {"description": "Not found"}},
                   )


@app.middleware("http")
async def db_session_middleware(request: Request, call_next):
    response = Response("Internal server error", status_code=500)
    try:
        request.state.db = SessionLocal()
        response = await call_next(request)
    finally:
        request.state.db.close()
    return response


@app.get("/")
async def root():
    return {"message": "Hello Bigger Applications!"}


if __name__ == '__main__':
    uvicorn.run(app, host="127.0.0.1", port=8888)
